package edu.nf.relaxenjoy.common.exception;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import edu.nf.relaxenjoy.common.result.ResultVO;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * @author zhu
 * @date 2024-10-12
 */
@RestControllerAdvice("edu.nf.relaxenjoy.controller")
public class ExceptionAdvice {

    @ExceptionHandler(value = { MethodArgumentNotValidException.class })
    public ResultVO handleValidException(MethodArgumentNotValidException e) throws JsonProcessingException {
        BindingResult result = e.getBindingResult();
        Map<String, String> errors = new HashMap<>();
        for (FieldError fieldError : result.getFieldErrors()) {
            errors.put(fieldError.getField(), fieldError.getDefaultMessage());
        }
        String json = new ObjectMapper().writeValueAsString(errors);
        ResultVO vo = new ResultVO();
        vo.setCode(10001);
        vo.setMessage(json);
        return vo;
    }

    @ExceptionHandler(value = { GlobalException.class })
    public ResultVO handleGlobalException(GlobalException e) {
        ResultVO vo = new ResultVO();
        vo.setCode(e.getErrorCode());
        vo.setMessage(e.getMessage());
        return vo;
    }

    @ExceptionHandler(value = { CommonException.class })
    public ResultVO handleValidatorException(CommonException e) {
        ResultVO vo = new ResultVO();
        vo.setCode(e.getCode());
        vo.setMessage(e.getMessage());
        return vo;
    }

    @ExceptionHandler(value = { Exception.class })
    public ResultVO handleException(Exception e) {
        e.printStackTrace();
        ResultVO vo = new ResultVO();
        vo.setCode(500);
        vo.setMessage("系统出现错误，请稍后重试");
        return vo;
    }
}
